package com.congee02;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * @author congee(congee02 @ 163.com)
 * @date 1/28/2023 6:36 PM
 */
public class PhantomReferenceTest {

    public static void main(String[] args) {
        // gc时会被直接回收
        Reference<PhantomSampleObject> reference = getPhantomReference();
        PhantomSampleObject object = reference.get();
        // 调用 get 始终返回 null
        System.out.println(object);
        System.gc();
        System.out.println("gc done");
    }

    private static Reference<PhantomSampleObject> getPhantomReference() {
        return new PhantomReference<>(new PhantomSampleObject(), new ReferenceQueue<>());
    }

    private static class PhantomSampleObject {
        @Override
        protected void finalize() throws Throwable {
            System.out.println("PhantomSampleObject: doing finalize");
        }
    }
}
